package udp.client;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

@SuppressWarnings({"all"})
public class UdpEchoClient {
    private DatagramSocket socket = null;
    public UdpEchoClient() throws SocketException {
        socket = new DatagramSocket(); // 在客户端，我们一般不自己指定端口号，而是由系统分配
    }

    public void start() throws IOException {
        while (true) {
            System.out.println("当前是客户端！");
            System.out.print(">");
            // 1、客户端从键盘输入请求的具体内容
            Scanner scanner = new Scanner(System.in);
            String request = scanner.nextLine();
            // 要说明要给谁发送请求，他的ip地址和端口号是多少（服务器的）
            // DatagramPacket requestPacket = new DatagramPacket(request.getBytes(), request.length(), InetAddress.getByName("127.0.0.1"), 8000);
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(), request.getBytes().length,
                    InetAddress.getByName("127.0.0.1"), 8000);
            // 2、客户端向服务器发送请求
            socket.send(requestPacket);
            // 3、客户端接收服务器返回的响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(responsePacket); // 注意我们是把服务器的响应存放到了responsePacket中，不要写错
            // 4、客户端显示服务器返回的响应信息,进行解析转换成String类型的信息
            String response = new String(responsePacket.getData(), 0, responsePacket.getLength());
            System.out.printf("发送方的ip地址和端口号：[%s:%s],  request: %s, response: %s\n", requestPacket.getAddress(), requestPacket.getPort(), request, response);
        }
    }
    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient();
        client.start();
    }
}
